import { Request, Response, NextFunction } from "express";
import { tokenPath } from "../config";
import { err, info } from "../router/middleware/infoerr";
import UserSer from "../services/UserSer";
export default async function (
  req: Request,
  res: Response,
  next: NextFunction
) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  const istoken = tokenPath.some(
    (item) => req.path === item.path && req.method === item.method
  );
  if (!istoken) return next();
  const token = req.signedCookies.feifan;
  if (!token) return err(res, "没有token");
  if (!token.name || !token.id) return err(res, "toke有误");
  const result = await UserSer.findistoken(token);
  if (!result)
    return err(res, "token信息错误", { 解决: "如果近期修改过密码请重新登录" });
  if (req.url === "/api/comment/submit" && req.method === "POST") {
    req.query = result;
    console.log(result);
  }

  if (req.path === "/api/user/islogin") return info(res, "ok", result);
  console.log(`用户${token.name} 访问了:${req.path}`);
  next();
}
